import React, { Component } from 'react'
import { Modal } from 'antd';
import Forms from '../Form'
import { addProducts, upDataProducts } from '../../../api/products'
export default class Layout extends Component {
    constructor(props) {
        super(props);
    }
    // 子组件完成挂载时, 将子组件的方法 this 作为参数传到父组件的函数中
    componentDidMount () {
        // 在子组件中调用父组件的方法, 并把当前的实例传进去
        this.props.onChildEvent(this)
    }
    state = {
        visible: false,
        formList: [
            {
                type: 'input',
                name: 'productName',
                label: '产品名称',
            },
            {
                type: 'upload',
                name: 'productImg',
                label: '产品图片',
            },
            {
                type: 'input',
                name: 'price',
                label: '价格',
            },
            {
                type: 'input',
                name: 'productType',
                label: '产品类型',
            }
        ],
        formData: [],
        type: 'add'
    }
    childVm = null
    addProducts = (data) => {
        addProducts({
          ...data
        }).then(res => {
           // console.log('res', res)
        })
    }
    upDataProducts = (data) => {
        upDataProducts({
            ...data
        }).then(res => {
            console.log('res', res)
            this.props.info.callback(data)
        })
    }
    openModal = (e) => {
        if (typeof e === 'object') {
            this.setState({formData: e})
            this.setState({type: 'upData'})
            if (this.childVm) {
                this.childVm.setFieldsValue(e, true)
            }
        }
        this.setState({ visible: true })
    }
    onChildEventFAun = childVm => {
        this.childVm = childVm
        this.childVm.setFieldsValue(this.state.formData, true)
    }
    handleOk = () => {
        this.setState({ visible: false})
        const data = this.childVm.getFieldsValue()
        if (this.state.type === 'add') {
            this.addProducts(data)
        } else {
            this.upDataProducts(data)
        }
    }
    handleCancel = () => {
        this.setState({ visible: false })
    }
    render() {
        const { visible, formList, formData } = this.state
        return (
            <div className={'AddProduct-box'}>
                <Modal
                    title={'添加产品'}
                    open={ visible }
                    onOk={ this.handleOk }
                    onCancel={ this.handleCancel }
                >
                  <Forms
                      onChildEventFAun={ this.onChildEventFAun }
                      formList={ formList }
                      formData={ formData }
                      noBtn={ true }
                  />
                </Modal>
            </div>
        )
    }
}
